/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TAREA_CATALOGO.java
 *
 * Created on 03-jul-2012, 17:00:25
 */
package Almacenamiento.Catalogos;

import Almacenamiento.Atributo;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import javax.swing.DefaultCellEditor;

import javax.swing.JComboBox;

import javax.swing.JFrame;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;

import javax.swing.JTable;

import javax.swing.SwingUtilities;

import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import Almacenamiento.Atributo.*;
import Almacenamiento.Relacion;
import javax.swing.Icon;

/**
 *
 * @author User
 */
public class TAREA_CATALOGO extends javax.swing.JFrame {
    //metabase
    /*
     * El catálogo de un sistema de base de datos no es más que una base de datos 
     * en sí misma a veces llamada metabase. Los contenidos de dicha base de datos son llamados metadatos. 
     * La función principal del catálogo es almacenar los esquemas de las bases 
     * de datos que el sistema mantiene.
     
     
     */
     List<EntradaCatalogo> Lista_Relaciones ;
     EntradaCatalogo entrada_actual;
     boolean Se_esta_modificando;
     boolean correcto;
    
    
    
    /** Creates new form TAREA_CATALOGO */
    public TAREA_CATALOGO() {
        initComponents();
        Lista_Relaciones= new ArrayList<EntradaCatalogo>();    
    jComboBox1.addItem("Create Table");

        jTextField1.setEnabled(true);
    
   String[] DATA = { "String", "Float", "Double", "Char", "Int", "Byte", "Short" ,"Long" };
    JComboBox comboBox = new JComboBox(DATA);
    comboBox.setSelectedIndex(0);
    DefaultCellEditor defaultCellEditor=new DefaultCellEditor(comboBox);
    jTable1.getColumnModel().getColumn(1).setCellEditor(defaultCellEditor);
   

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        jSeparator3 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Juice ITC", 0, 24)); // NOI18N
        jLabel1.setText("Nombre Tabla:");

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setFont(new java.awt.Font("Juice ITC", 0, 18)); // NOI18N
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null}
            },
            new String [] {
                "Atributos", "Tipo"
            }
        ));
        jScrollPane2.setViewportView(jTable1);

        jButton2.setFont(new java.awt.Font("Juice ITC", 0, 18)); // NOI18N
        jButton2.setIcon(new javax.swing.ImageIcon("D:\\iconos verdes\\guardar.PNG")); // NOI18N
        jButton2.setText("Crear Tabla");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setFont(new java.awt.Font("Juice ITC", 0, 18)); // NOI18N
        jButton3.setIcon(new javax.swing.ImageIcon("D:\\iconos verdes\\mas.PNG")); // NOI18N
        jButton3.setText("Atributo");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jComboBox1.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cambio(evt);
            }
        });
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Juice ITC", 0, 24)); // NOI18N
        jLabel2.setText(" Ver Tabla");

        jButton1.setFont(new java.awt.Font("Juice ITC", 0, 18)); // NOI18N
        jButton1.setIcon(new javax.swing.ImageIcon("D:\\iconos verdes\\modificar.PNG")); // NOI18N
        jButton1.setText("Modificar Tabla");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton4.setFont(new java.awt.Font("Juice ITC", 0, 18)); // NOI18N
        jButton4.setIcon(new javax.swing.ImageIcon("D:\\iconos verdes\\eliminar2.PNG")); // NOI18N
        jButton4.setText("Eliminar Tabla");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Juice ITC", 0, 24)); // NOI18N
        jLabel3.setText("Nombre Archivo:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSeparator3, javax.swing.GroupLayout.DEFAULT_SIZE, 650, Short.MAX_VALUE)
                .addGap(69, 69, 69))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(48, 48, 48)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 338, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel1)
                                .addComponent(jLabel3))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 337, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 337, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jButton2))))
                .addGap(91, 91, 91))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(50, 50, 50)
                .addComponent(jButton3)
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
                        .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE))
                .addGap(93, 93, 93))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jTextField1)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3)))
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(48, 48, 48)
                        .addComponent(jButton3)))
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(49, 49, 49))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
//
     Se_esta_modificando=false;
    if ("".equals(jTextField1.getText()) ) {
         for(int b=0;b<jTable1.getRowCount()-1;b++){ 
          
          DefaultTableModel dtm= (DefaultTableModel) jTable1.getModel();
          dtm.removeRow(b); 
            }
        JOptionPane.showMessageDialog(this,"Debe  ingresar el nombre de la Tabla");
        //JOptionPane.showMessageDialog(this, "Debe  ingresar el nombre de la Tabla", null, WIDTH, new Icon() {})
    }
    else
    {
    Relacion R= new Relacion();
    List<Atributo> att= new ArrayList<Atributo>();
    int nro = jTable1.getRowCount();
    
    for (int i = 0; i < nro; i++) {
        try{
            
        String clase= jTable1.getValueAt(i, 1).toString();
        
        if ("String".equals(clase)) {
            
            att.add(new Atributo(jTable1.getModel().getValueAt(i, 0).toString(),String.class));
        }
        if ("Int".equals(clase)) {
            att.add(new Atributo(jTable1.getModel().getValueAt(i, 0).toString(),Integer.class));
        }
        if ("Long".equals(clase)) {
            att.add(new Atributo(jTable1.getModel().getValueAt(i, 0).toString(),Long.class));
        }
        if ("Char".equals(clase)) {
            att.add(new Atributo(jTable1.getModel().getValueAt(i, 0).toString(),Character.class));
        }
         if ("Double".equals(clase)) {
            att.add(new Atributo(jTable1.getModel().getValueAt(i, 0).toString(),Double.class));
        }
          if ("Float".equals(clase)) {
            att.add(new Atributo(jTable1.getModel().getValueAt(i, 0).toString(),Float.class));
        }
           if ("Shor".equals(clase)) {
            att.add(new Atributo(jTable1.getModel().getValueAt(i, 0).toString(),Short.class));
        }
         if ("Byte".equals(clase)) {
            att.add(new Atributo(jTable1.getModel().getValueAt(i, 0).toString(),Byte.class));
        }
         correcto=true;
        }
        catch(Exception r) // en caso de tupla vacia
        {
            if (    att.isEmpty()) { //totalmente incorrecto
                JOptionPane.showMessageDialog(this,"Tiene que agregar al menos un atributo");
                correcto=false;
                break;
                
            }
            else
            {
           
            correcto=true;
            }
            
        }
    }
    //fin de for
    
    
    
        if (correcto==true) {
            
        
     R.setAtributos(att);
    
    //JTable tabla_r= new JTable();
    //agregando dinamicamente tablas
    
    EntradaCatalogo en1 = null;
                try {
                    en1 = new EntradaCatalogo(new Tabla(jTextField1.getText(),att));
                } catch (IOException ex) {
                    Logger.getLogger(TAREA_CATALOGO.class.getName()).log(Level.SEVERE, null, ex);
                }
    entrada_actual= en1 ;
    jComboBox1.addItem(en1.getNombreTabla());
     Lista_Relaciones.add(en1);
     entrada_actual=en1;
    JOptionPane.showMessageDialog(this,"La tabla se agregó correctamente");
   
    jComboBox1.setSelectedItem(jTextField1.getText());
    
    
    //vaciar todo
   
    
    jTextField1.setText("");
    jComboBox1.setSelectedItem("Create Table");
    
    
         
           
     for(int b=0;b<jTable1.getRowCount()-1;b++){ 
          
          DefaultTableModel dtm= (DefaultTableModel) jTable1.getModel();
          dtm.removeRow(b); 
            }
        
        
        
        }
        }

    
}//GEN-LAST:event_jButton2ActionPerformed

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed



((DefaultTableModel)
jTable1.getModel()).setRowCount(jTable1.getRowCount()+1);

//jTable2.setModel(modelo);
    
    
    
}//GEN-LAST:event_jButton3ActionPerformed

private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed

    
    
}//GEN-LAST:event_jComboBox1ActionPerformed

private void cambio(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cambio
 
    if (jComboBox1.getSelectedItem()=="Create Table") {
        
         jTextField1.setEnabled(true);
         jButton2.setEnabled(true);
         jButton1.setEnabled(false);
         jButton4.setEnabled(false);
        
    }
    else{
    
     jTextField1.setEnabled(false);
     jButton2.setEnabled(false);
       jButton1.setEnabled(true);
         jButton4.setEnabled(true);
    }             
     if (Se_esta_modificando==false) {
            for(int b=0;b<jTable1.getRowCount()-1;b++){ 
          
          DefaultTableModel dtm= (DefaultTableModel) jTable1.getModel();
          dtm.removeRow(b); 
            } 
        }
     
    //mostrar la tabla seleccionada
    for (int i = 0; i < Lista_Relaciones.size(); i++) {
        if (Lista_Relaciones.get(i).getNombreTabla() == jComboBox1.getSelectedItem()) {
           
                  
           	
            //volcar los atributos actuales
            List<Atributo> at_actual = Lista_Relaciones.get(i).getTabla().getAtributos();
            for (int j = 0; j < at_actual.size(); j++) {
                
               ((DefaultTableModel)
jTable1.getModel()).setRowCount(jTable1.getRowCount()+1);
                
                jTable1.setValueAt(at_actual.get(j).getNombre(), j, 0);
                String tipo = at_actual.get(j).getTipo().toString().substring(16);
                jTable1.setValueAt(tipo, j, 1);
                
                
                
            }
            
            
            //i=Lista_Relaciones.size() -1;
        }
        
    }
    
    
}//GEN-LAST:event_cambio

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
    Se_esta_modificando=true;
    jTextField1.setEnabled(true);
    //eliminar la tabla actual
    
    for (int i = 0; i < Lista_Relaciones.size(); i++) {
        
        if (Lista_Relaciones.get(i).getNombreTabla() ==jComboBox1.getSelectedItem() ){
            entrada_actual=Lista_Relaciones.get(i);
        }
        
    }
    Lista_Relaciones.remove(entrada_actual);
    jTextField1.setText(entrada_actual.getNombreTabla());
    jButton1.setEnabled(false);
    jButton4.setEnabled(false);
    jComboBox1.removeItem(entrada_actual.getNombreTabla());
    jComboBox1.setSelectedItem("Create Table");
    
    
    
           
}//GEN-LAST:event_jButton1ActionPerformed

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
// TODO add your handling code here:
    
    for(int b=0;b<jTable1.getRowCount()-1;b++){ 
          
          DefaultTableModel dtm= (DefaultTableModel) jTable1.getModel();
          dtm.removeRow(b); 
            } 
    jComboBox1.removeItem(entrada_actual.getNombreTabla());
    Lista_Relaciones.remove(entrada_actual);
    jButton1.setEnabled(false);
    jButton4.setEnabled(false);
    jComboBox1.setSelectedItem("Create Table");
    
}//GEN-LAST:event_jButton4ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TAREA_CATALOGO.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TAREA_CATALOGO.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TAREA_CATALOGO.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TAREA_CATALOGO.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new TAREA_CATALOGO().setVisible(true);
            }
        });
    }
    //directory.getCanonicalPath().toString()+"\\mantenimiento.ser"
    
    
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration//GEN-END:variables
}
